package myJs.search.detail

import myJs.Implicits._
import myJs.api.Api
import myJs.cps._
import myJs.myPkg.{MyFetch, ReactRouterDOM, SwalOptions, swal}
import shared.Pojo._
import myJs.tool.Tool
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.web.html._

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.reactBootstrap.{OverlayTrigger, Popover}
import myJs.search.Search
import org.scalajs.dom.window
import upickle.default._

import scala.collection.immutable.SeqMap
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.tsPojo.TsPojo
import slinky.core.facade.ReactElement
import typings.csstype.csstypeStrings

/** Created by yz on 21/1/2022
  */
@react object HTissueCp {

  case class Props(showLoading: Boolean = true, geneName: String)
  val groupMap = List("Phenotype", "Age", "Sex", "Inflammation", "Fibrosis", "Tumor.stage", "Tumor.grade").optionMap
  val initPhenotypes = List(
    "Fetal",
    "Normal",
    "NAFLD",
    "ALD",
    "Viral Hepatitis",
    "Fibrosis",
    "Cirrhosis",
    "Dysplastic Nodule",
    "HCC",
    "ICC",
    "Mixed HCC-ICC",
    "HB"
  )

  val component = FunctionalComponent[Props] { props =>
    val (phenotypes, setPhenotypes) = useState(initPhenotypes)
    val (datasets, setDatasets) = useState(List.empty[String])
    val (hasRefreshDatasetMap, setHasRefreshDatasetMap) = useState(false)
    val (group, setGroup) = useState("Phenotype")
    val (imgSrc, setImgSrc) = useState("")
    val (geneName, setGeneName) = useState(props.geneName)
    val (isLog, setIsLog) = useState(false)
    val (datasetMap, setDatasetMap) = useState(SeqMap[String, String]())
    val navigate = ReactRouterDOM.useNavigate()
    val (geneData, setGeneData) = useState("")

    object FTool {

      def refreshImg = () => {
        import TsPojo.browseGene._
        Tool.useLoadingF(showLoading = props.showLoading) { () =>
          val log = if (isLog) "Yes" else "No"
          val request = HTissueBoxplotImage.Request(
            geneName = geneName,
            phenotypes = phenotypes,
            group = group,
            datasets = datasets,
            log = log
          )
          Api.browseGene.hTissueBoxplotImage(request).map { response =>
            if (response.valid) {
              val src = s"data:image/png;base64,${response.base64}"
              setImgSrc(src)
              setGeneData(response.geneData)
            } else {
              val options = SwalOptions(title = "Error", text = response.message, `type` = "error")
              swal(options)
            }
          }
        }
        ()
      }

      def groupChange = (v: String) => {
        setGroup(v)
      }

      def phenotypesChange = (vs: List[String]) => {
        setPhenotypes(vs)
      }

      def datasetsChange = (vs: List[String]) => {
        setDatasets(vs)
      }

      def reset = () => {
        setGroup("Phenotype")
        setPhenotypes(initPhenotypes)
        setDatasets(datasetMap.keyList)
        setIsLog(false)
      }

      def geneNameChange = (v: String) => {
        setGeneName(v)
      }

      def isLogChange = (v: Boolean) => {
        setIsLog(v)
      }

      def refreshDatasetMap = {
        Api.getFileColumn("hbulk_meta.txt", "Dataset").map { rs =>
          val curDatasetMap = rs.optionMap
          setDatasetMap(curDatasetMap)
          setDatasets(curDatasetMap.keyList)
          setHasRefreshDatasetMap(true)
        }
      }

      def downloadCsv = () => {
        Tool.downloadCsv(s"${props.geneName}.csv", geneData)
      }

      def downloadPng = () => {
        Tool.downloadPng(imgSrc = imgSrc, fileName = s"${props.geneName}.png")
      }

      def downloadJpeg = () => {
        Tool.downloadJpeg(imgSrc = imgSrc, fileName = s"${props.geneName}.jpeg")
      }

      def downloadPdf = () => {
        Tool.downloadPdf(imgSrc = imgSrc, fileName = s"${props.geneName}.pdf")
      }

      def downloadSvg = () => {
        Tool.downloadSvg(imgSrc = imgSrc, fileName = s"${props.geneName}.svg")
      }

    }

    useEffect(
      () => {
        if (hasRefreshDatasetMap) {
          FTool.refreshImg()
          setHasRefreshDatasetMap(false)
        }
      },
      List(hasRefreshDatasetMap)
    )

    useEffect(
      () => {
        FTool.refreshDatasetMap
      },
      List()
    )

    useEffect(
      () => {
        if (geneName != props.geneName) {
          val url = s"${Detail.absolutePath}?geneName=${geneName}&species=Hsa"
          navigate(s"${url}")
        }
      },
      List(geneName)
    )

    div(
      style := Style(display = csstypeStrings.flex),
      div(
        style := Style(flex = 3, width = "30%"),
        form(
          style := Style(),
          id := "form",
          div(
            style := Style(marginRight = 15),
            className := "form-group",
            div(style := Style(), label(style := Style(), className := "control-label", "Gene Symbol")),
            div(
              style := Style(height = 34, display = csstypeStrings.flex, alignItems = csstypeStrings.center), {
                val url = s"${Api.apiUrl}/gepLiver/analysis/getAllGene"
                PureAsyncSelect2Cp(width = "100%", onChange = FTool.geneNameChange, value = geneName, url = url)
              }
            )
          ),
          div(
            style := Style(),
            HFilterCp(
              phenotypes = phenotypes,
              phenotypesChange = FTool.phenotypesChange,
              datasets = datasets,
              datasetsChange = FTool.datasetsChange,
              datasetMap = datasetMap
            )
          ),
          div(
            style := Style(marginRight = 15),
            className := "form-group",
            div(style := Style(), label(style := Style(), className := "control-label", "Group By")),
            div(
              style := Style(height = 34, display = csstypeStrings.flex, alignItems = csstypeStrings.center),
              PureSelect2Cp(
                optionMap = groupMap,
                value = group,
                onChange = FTool.groupChange,
                width = "100%",
              )
            )
          ),
          div(
            style := Style(display = csstypeStrings.flex, marginRight = 15, alignItems = csstypeStrings.center),
            className := "form-group",
            div(
              style := Style(flex = 2, display = csstypeStrings.flex),
              label(style := Style(), className := "control-label", "Log", sub("2"), "(TPM+1):")
            ),
            div(
              style := Style(flex = 3, height = 34, paddingLeft = 15, paddingRight = 15),
              className := "col-sm-3",
              PureToggleCp(value = isLog, valueChange = FTool.isLogChange)
            )
          ),
          div(
            style := Style(),
            className := "form-group",
            div(
              style := Style(),
              className := "actions",
              button(
                style := Style(width = "95%"),
                `type` := "button",
                className := "btn btn-primary myBtn",
                onClick := FTool.refreshImg,
                s" Plot"
              )
            ),
            div(
              style := Style(),
              className := "actions",
              button(
                style := Style(width = "95%"),
                `type` := "button",
                className := "btn btn-primary myBtn",
                onClick := FTool.reset,
                s" Reset"
              )
            )
          )
        )
      ),
      div(
        style := Style(flex = 7),
        div(
          style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.`flex-end`),
          a(
            onClick := FTool.downloadCsv,
            className := "btn  btn-default",
            title := "Export data",
            i(className := "glyphicon glyphicon-export")
          ),
          div(
            style := Style(marginLeft = 5),
            className := "btn-group",
            a(
              title := "Export image",
              className := "btn  btn-default idsButton",
              data - "toggle" := "dropdown",
              data - "hover" := "dropdown",
              data - "close-others" := "true",
              aria - "expanded" := "false",
              i(className := "fa fa-bars")
            ),
            ul(
              className := "dropdown-menu pull-right",
              li(
                a(onClick := FTool.downloadPng, "Download PNG image")
              ),
              li(
                a(onClick := FTool.downloadJpeg, "Download JPEG image")
              ),
              li(
                a(onClick := FTool.downloadPdf, "Download PDF image")
              ),
              li(
                a(onClick := FTool.downloadSvg, "Download SVG image")
              )
            )
          )
        ),
        img(className := "mySvg", id := "boxplotImg", src := imgSrc),
        OrthologCp(geneName = geneName, species = "Hsa")
      )
    )

  }

  object STool {}

}
